package com.ktgj.flight.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.FlightOrderChangeConstants;
import com.ktgj.common.core.constant.FlightOrderConstants;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.customer.api.domain.CustomerIdVoApi;
import com.ktgj.flight.domain.*;
import com.ktgj.flight.domain.vo.*;
import com.ktgj.flight.mapper.*;
import com.ktgj.flight.service.IFlightOrderChangeTicketsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.flight.service.IFlightOrderChangeService;
import org.yaml.snakeyaml.events.Event;

/**
 * 机票预订_机票退改签废订单信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-10-26
 */
@Service
public class FlightOrderChangeServiceImpl implements IFlightOrderChangeService 
{
    @Autowired
    private FlightOrderChangeMapper flightOrderChangeMapper;

    @Autowired
    private FlightOrderInfoTicketsMapper orderInfoTicketsMapper;

    @Autowired
    private FlightRefundRequestMapper refundRequestMapper;

    @Autowired
    private RemoteCustomerService customerService;

    @Autowired
    private FlightOrderChangeTicketsMapper changeTicketsMapper;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @Autowired
    private FlightOrderInfoTicketsMapper flightOrderInfoTicketsMapper;

    @Autowired
    private FlightOrderInfoMapper flightOrderInfoMapper;

    /**
     * 查询机票预订_机票退改签废订单信息
     * 
     * @param changeOrderId 机票预订_机票退改签废订单信息ID
     * @return 机票预订_机票退改签废订单信息
     */
    @Override
    public FlightOrderChange selectFlightOrderChangeById(String changeOrderId)
    {
        return flightOrderChangeMapper.selectFlightOrderChangeById(changeOrderId);
    }

    /**
     * 查询机票预订_机票退改签废订单信息列表
     * 
     * @param flightOrderChange 机票预订_机票退改签废订单信息
     * @return 机票预订_机票退改签废订单信息
     */
    @Override
    public List<FlightOrderChange> selectFlightOrderChangeList(FlightOrderChange flightOrderChange)
    {
        return flightOrderChangeMapper.selectFlightOrderChangeList(flightOrderChange);
    }

    /**
     * 新增机票预订_机票退改签废订单信息
     * 
     * @param flightOrderChange 机票预订_机票退改签废订单信息
     * @return 结果
     */
    @Override
    public int insertFlightOrderChange(FlightOrderChange flightOrderChange)
    {
        flightOrderChange.setCreateTime(DateUtils.getNowDate());
        return flightOrderChangeMapper.insertFlightOrderChange(flightOrderChange);
    }

    /**
     * 修改机票预订_机票退改签废订单信息
     * 
     * @param flightOrderChange 机票预订_机票退改签废订单信息
     * @return 结果
     */
    @Override
    public int updateFlightOrderChange(FlightOrderChange flightOrderChange)
    {
        return flightOrderChangeMapper.updateFlightOrderChange(flightOrderChange);
    }

    /**
     * 批量删除机票预订_机票退改签废订单信息
     * 
     * @param changeOrderIds 需要删除的机票预订_机票退改签废订单信息ID
     * @return 结果
     */
    @Override
    public int deleteFlightOrderChangeByIds(Long[] changeOrderIds)
    {
        return flightOrderChangeMapper.deleteFlightOrderChangeByIds(changeOrderIds);
    }

    /**
     * 删除机票预订_机票退改签废订单信息信息
     * 
     * @param changeOrderId 机票预订_机票退改签废订单信息ID
     * @return 结果
     */
    @Override
    public int deleteFlightOrderChangeById(Long changeOrderId)
    {
        return flightOrderChangeMapper.deleteFlightOrderChangeById(changeOrderId);
    }

    /**
     * 退票申请
     * @param
     * @return
     */
    @Override
    public Map<String, Object> orderChangeTickets(Long orderId) {
        Map<String, Object> ticketsMap = new HashMap<>();
        List<FlightOrderInfoTickets> flightOrderInfoTickets = orderInfoTicketsMapper.selectFlightOrderInfoTicketsByOrderId(orderId);
        List<Map<String, Object>> infoTicketList = new ArrayList();
        for (FlightOrderInfoTickets infoTicket : flightOrderInfoTickets) {
            Map<String, Object> infoTicketMap = new HashMap<>();
            infoTicketMap.put("OrderInfoTicketsId", infoTicket.getOrderInfoTicketsId());
            infoTicketMap.put("Departure", infoTicket.getDeparture());
            infoTicketMap.put("Arrival", infoTicket.getArrival());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = dateFormat.format(infoTicket.getDepartureTime());
            infoTicketMap.put("DepartureTime", format);
            infoTicketMap.put("GuestName", infoTicket.getGuestName());
            infoTicketMap.put("TripType", infoTicket.getTripType());
            infoTicketMap.put("TicketNo", infoTicket.getTicketNo());
            infoTicketList.add(infoTicketMap);
        }
        ticketsMap.put("orderId", orderId);
        ticketsMap.put("FlightInformation", infoTicketList);
        Map<String, Object> payMap = new HashMap<>();
        payMap.put("Wechat", BusinessTypeConstants.Wechat.getValue());
        payMap.put("Alipay", BusinessTypeConstants.Alipay.getValue());
        ticketsMap.put("PaymentReturn", payMap);
        return ticketsMap;
    }

    /**
     * 申请退票
     * @param
     * @return
     */
    @Override
    public int insertOrderChangeTickets(String refundReason, Long orderId, String pdfContent) {
        FlightOrderChange orderChange = new FlightOrderChange();
        Long changeOrderId = System.currentTimeMillis() / 1000;
        orderChange.setChangeOrderId(changeOrderId + "-T");
        orderChange.setIsdealing("0");
        orderChange.setRefundReason(refundReason);
        orderChange.setOrderId(String.valueOf(orderId));
        orderChange.setChangeStatus("0");

        if (pdfContent != null && pdfContent != "") {
            String[] split = pdfContent.split("&");
            String str = "2|";
            for (int i = 0 ; i < split.length ; i++) {
                for (String pdf : split) {
                    str = str + pdf;
                    if (i + 1 < split.length){
                        str = str + ",";
                    }
                }
            }
            orderChange.setRefundContent(str); //非自愿退票所需材料(2|1,2,3)
        }

        orderChange.setCheckStatus("1");
        orderChange.setRefundstatus("0");
        orderChange.setApirefundstatus("1");
        orderChange.setRefundServiceFee(new BigDecimal(20.00));
        orderChange.setAddTime(new Date());
        flightOrderChangeMapper.insertFlightOrderChange(orderChange);
        FlightRefundRequest refundRequest = new FlightRefundRequest();
        refundRequest.setOrderId(orderId);
        refundRequest.setRequestTime(new Date());
        refundRequest.setStatusId(FlightOrderConstants.refundTicketStatus_create.getValue());
        refundRequest.setChangeOrderId(changeOrderId + "-T");
        return refundRequestMapper.insertFlightRefundRequest(refundRequest);
    }

    /**
     * 根据订单号获取退票申请
     * @param orderNo
     * @return
     */
    @Override
    public FlightOrderChange getFlightOrderChangeInfoByOrderNo(String orderNo) {
        return refundRequestMapper.getFlightOrderChangeInfoByOrderNo(orderNo);
    }

    /**
     * 退改签查询机票订单性情
     * @param flightRefundChange
     * @return
     */
    @Override
    public List<FlightRefundChange> selectFlightReturnChange(FlightRefundChange flightRefundChange) {
        List<FlightRefundChange> refundChangeList = flightOrderChangeMapper.selectFlightReturnChange(flightRefundChange);
        for (FlightRefundChange refundChange : refundChangeList) {
            if (refundChange.getStatus().equals("2")){
                refundChange.setGustNameReturn(refundChange.getGustName());
            }
        }
        return refundChangeList;
    }

    @Override
    public FlightOrderPending selectFlightOrderPendingById(String orderId) {
        return flightOrderChangeMapper.selectFlightOrderPendingById(orderId);
    }

    @Override
    public List<FlightOrderPending> selectFlightOrderPending(FlightOrderPending flightOrderPending) {
        return flightOrderChangeMapper.selectFlightOrderPending(flightOrderPending);
    }

    //退改签订单列表
    @Override
    public List<FlightOrderChangeVO> queryOrderChangeList(FlightOrderChangeTicketsDto tickets) {
        if (tickets.getCustomerName() != null && tickets.getCustomerName() != "") {
            Customer customer = new Customer();
            customer.setCustomerName(tickets.getCustomerName());
            List<Customer> customers = customerService.customerList(customer);
            customers.forEach(item -> {
                tickets.getCustomerId().add(item.getCustomerId());
            });
        }
        if (!tickets.isChange()) {
            tickets.setChangeType(FlightOrderChangeConstants.refund.getValue());
        }
        if (tickets.getCreateTimeEnd() != null && tickets.getCreateTimeEnd() != "") {
            StringBuilder builder = new StringBuilder();
            builder.append(tickets.getCreateTimeEnd());
            builder.append(" 23:59:59");
            tickets.setCreateTimeEnd(builder.toString());
        }
        List<FlightOrderChangeVO> changeList = flightOrderChangeMapper.queryOrderChangeList(tickets);
        changeList.forEach(item -> {
            List<FlightOrderChangeTickets> ticketsList = changeTicketsMapper.refundFlightOrder(item.getChangeOrderId());
            item.setGuestNum(Long.valueOf(ticketsList.size()));
            ticketsList.forEach(items -> {
                FlightOrderChangeTicketsVO ticketsVO = new FlightOrderChangeTicketsVO();
                BeanUtils.copyProperties(items, ticketsVO);
                item.getOrderChangeTickets().add(ticketsVO);
            });
            boolean match = ticketsList.stream().allMatch(items -> items.getGuestPymtStsId() != null && items.getGuestPymtStsId().equals(FlightOrderConstants.waitPay.getValue()));
            if (match) {
                item.setChangeStatus("0");
            }
        });
        return changeList;
    }

    //退改签订单详情
    @Override
    public FlightChangeOrderVO queryOrderChange(String changeOrderId) {
        FlightChangeOrderVO change = new FlightChangeOrderVO();
        FlightOrderChangeTicketsDto tickets = new FlightOrderChangeTicketsDto();
        tickets.setChangeOrderId(changeOrderId);
        List<FlightOrderChangeVO> changeList = flightOrderChangeMapper.queryOrderChangeList(tickets);
        List<FlightOrderChangeTickets> ticketsList = changeTicketsMapper.refundFlightOrder(changeList.get(0).getChangeOrderId());
        BeanUtils.copyProperties(changeList.get(0), change);
        change.setGuestNum(Long.valueOf(ticketsList.size()));
        ticketsList.forEach(items -> {
            FlightChangeOrderTicketsVO ticketsVO = new FlightChangeOrderTicketsVO();
            BeanUtils.copyProperties(items, ticketsVO);
            ticketsVO.setChangeTicketId(String.valueOf(items.getChangeTicketId()));
            change.getOrderTickets().add(ticketsVO);
        });
        return change;
    }

    /**
     * 机票改签详情
     * */
    @Override
    public OrderFlightDetails selectOrderChangeDetails(String changeOrderId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        OrderFlightDetails orderFlightDetails = new OrderFlightDetails();
        FlightOrderChangeTicketsDto tickets = new FlightOrderChangeTicketsDto();
        tickets.setChangeOrderId(changeOrderId);
        List<FlightOrderChangeVO> changeList = flightOrderChangeMapper.queryOrderChangeList(tickets);
        List<FlightOrderChangeTickets> ticketsList = changeTicketsMapper.refundFlightOrder(changeList.get(0).getChangeOrderId());

        if (ticketsList.size() <= 0){
            throw new Exception("未查到机票订单详细信息");
        }

        Long customerId = ticketsList.get(0).getCustomerId();
        CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
        customerIdVoApi.setCustomerId(customerId);
        CustomerIdVoApi tmpCustomerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);
        orderFlightDetails.setCustomerName(tmpCustomerIdVoApi.getCustomerName());
        orderFlightDetails.setCustomerCardId(tmpCustomerIdVoApi.getCustomerCard());
        orderFlightDetails.setContactMobile(tmpCustomerIdVoApi.getCustomerPhone());
        if (ticketsList.get(0).getOrderId() != null && ticketsList.get(0).getOrderId() != 0){
            orderFlightDetails.setOrderNum(ticketsList.get(0).getOrderId().toString());
        }

        List<PassengerInformation> passenger = new ArrayList<>();
        for (FlightOrderChangeTickets flightOrderChangeTickets : ticketsList) {
            PassengerInformation passengerInformation = new PassengerInformation();
            passengerInformation.setGuestName(flightOrderChangeTickets.getGuestName());
            passengerInformation.setGuestType(flightOrderChangeTickets.getGuestType());
            passengerInformation.setGuestIdno(flightOrderChangeTickets.getGuestIdno());
            passengerInformation.setTicketNo(flightOrderChangeTickets.getTicketNo());
            passenger.add(passengerInformation);
        }

        orderFlightDetails.setPassenger(passenger);

        List<FlightOrderInfoTickets> infoTickets = flightOrderInfoTicketsMapper.selectFlightOrderInfoTicketsByOrderId(Long.valueOf(changeList.get(0).getOrderId()));
        FlightOrderInfo orderInfo = flightOrderInfoMapper.selectFlightOrderInfoById(Long.valueOf(changeList.get(0).getOrderId()));
        orderFlightDetails.setId(String.valueOf(orderInfo.getOrderId()));

        List<OutboundVo> outboundVoList = null;
        OutboundVo journeyVo = null;

        if (orderInfo.getTripType().equals("ow")){
            for (FlightOrderInfoTickets infoTicket : infoTickets) {
                if ((outboundVoList == null && infoTicket.getTripType().equals("ow")) ||
                        (outboundVoList != null && infoTicket.getTripType().equals("ot"))){
                    outboundVoList = new ArrayList<>();
                    OutboundVo outboundVo = new OutboundVo();
                    outboundVo.setOutbound(infoTicket.getDeparture());
                    outboundVo.setPosition(infoTicket.getCabinGrade());
                    outboundVo.setFlight(infoTicket.getFlight());
                    outboundVo.setFlightTime(format.format(infoTicket.getDepartureTime()));
                    outboundVo.setArrivalTime(format.format(infoTicket.getArrivalTime()));
                    outboundVo.setAirline(infoTicket.getAirliner());
                    outboundVoList.add(outboundVo);
                }
                else {
                    throw new Exception(infoTicket.getOrderInfoTicketsId() + "没有明确的单程往返信息");
                }
            }
        }
        else if (orderInfo.getTripType().equals("rt")){
            for (FlightOrderInfoTickets infoTicket : infoTickets) {
                if (outboundVoList == null && infoTicket.getTripType().equals("ow")){
                    outboundVoList = new ArrayList<>();
                    OutboundVo outboundVo = new OutboundVo();
                    outboundVo.setOutbound(infoTicket.getDeparture());
                    outboundVo.setPosition(infoTicket.getCabinGrade());
                    outboundVo.setFlight(infoTicket.getFlight());
                    outboundVo.setFlightTime(format.format(infoTicket.getDepartureTime()));
                    outboundVo.setArrivalTime(format.format(infoTicket.getArrivalTime()));
                    outboundVo.setAirline(infoTicket.getAirliner());
                    outboundVoList.add(outboundVo);
                }
                else if (journeyVo == null && infoTicket.getTripType().equals("rt")){
                    journeyVo = new OutboundVo();
                    journeyVo.setOutbound(infoTicket.getDeparture());
                    journeyVo.setPosition(infoTicket.getCabinGrade());
                    journeyVo.setFlight(infoTicket.getFlight());
                    journeyVo.setFlightTime(format.format(infoTicket.getDepartureTime()));
                    journeyVo.setArrivalTime(format.format(infoTicket.getArrivalTime()));
                    journeyVo.setAirline(infoTicket.getAirliner());
                }
                else {
                    throw new Exception(infoTicket.getOrderInfoTicketsId() + "没有明确的单程往返信息");
                }
            }
        }
        else {
            throw new Exception(changeList.get(0).getOrderId() + "没有明确的单程往返信息");
        }

        orderFlightDetails.setOutboundVo(outboundVoList);
        orderFlightDetails.setJourneyVo(journeyVo);

        PriceDetailsVo priceDetailsVo = new PriceDetailsVo();
        if (infoTickets.get(0).getTicketPrice() != null && infoTickets.get(0).getTicketPrice().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setFaceValue(infoTickets.get(0).getTicketPrice().toString());
        }

        if (infoTickets.get(0).getAirportFee() != null && infoTickets.get(0).getAirportFee().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setMachineCost(infoTickets.get(0).getAirportFee().toString());
        }

        if (infoTickets.get(0).getFuelFee() != null && infoTickets.get(0).getFuelFee().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setFuelCosts(infoTickets.get(0).getFuelFee().toString());
        }

        if (infoTickets.get(0).getInsuranceAmount() != null && infoTickets.get(0).getInsuranceAmount().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setInsurance(infoTickets.get(0).getInsuranceAmount().toString());
        }

        if (orderInfo.getAdditionalFee() != null && orderInfo.getAdditionalFee().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setAdditionalFeeOne(orderInfo.getAdditionalFee().toString());
        }

        if (orderInfo.getPayAmount() != null && orderInfo.getPayAmount().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setActuallyPayable(orderInfo.getPayAmount().toString());
        }

        if (orderInfo.getTicketAmount() != null && orderInfo.getTicketAmount().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setTotalFare(orderInfo.getTicketAmount().toString());
        }

        if (orderInfo.getPayMinus() != null && orderInfo.getPayMinus().compareTo(new BigDecimal(0)) > 0){
            priceDetailsVo.setDiscount(orderInfo.getPayMinus().toString());
        }

        if (orderInfo.getGuestNum() != null && orderInfo.getGuestNum() != 0){
            priceDetailsVo.setTicketsNumber(orderInfo.getGuestNum().toString());
        }

        orderFlightDetails.setPriceDetailsVo(priceDetailsVo);
        return orderFlightDetails;
    }

    /**
     * 退票订单列表
     * */
    @Override
    public List<FlightOrderChange> refundList(String airline, String start, String end) {
        List<FlightOrderChange> flightOrderChanges = flightOrderChangeMapper.refundList(start, end);
        List<FlightOrderChange> flightOrderChangeList = new ArrayList<>();
        for (FlightOrderChange flightOrderChange : flightOrderChanges) {
            List<FlightOrderChangeTickets> flightOrderChangeTickets = changeTicketsMapper.selectFlightOrderChangeTickets(flightOrderChange.getChangeOrderId());
            if (flightOrderChangeTickets.size() > 0){
                if (flightOrderChangeTickets.get(0).getAirliner().equals(airline)){
                    FlightOrderChange tmpFlightOrderChange = new FlightOrderChange();
                    tmpFlightOrderChange.getChangeTicketsList().addAll(flightOrderChangeTickets);
//                    for (FlightOrderInfoTickets flightOrderInfoTicket : flightOrderInfoTickets) {
//                        flightOrderChangeList.add(flightOrderInfoTicket);
//                    }
                }
            }
        }
        return flightOrderChangeList;
    }

    /**
     * 会员手机号获取机票退票单
     * */
    @Override
    public List<FlightOrderChange> refundForm(String phone) {
        List<FlightOrderChange> flightOrderChangeList = new ArrayList<>();
        CustomerIdVoApi customerIdVoApi = new CustomerIdVoApi();
        customerIdVoApi.setCustomerPhone(phone);
        customerIdVoApi = remoteCustomerService.customerIdApi(customerIdVoApi);
        if (customerIdVoApi != null){
            List<FlightOrderList> flightOrderLists = flightOrderInfoMapper.flightOrderInfoList(customerIdVoApi.getCustomerId());
            if (flightOrderLists.size() > 0){
                for (FlightOrderList flightOrderList : flightOrderLists) {
                    List<FlightOrderChange> flightOrderChanges = flightOrderChangeMapper.queryFlightOrderChangeByOrderId(flightOrderList.getOrderId());
                    if (flightOrderChanges.size() > 0){
                        for (FlightOrderChange flightOrderChange : flightOrderChanges) {
                            if (flightOrderChange.getChangeType().equals("refund")){
                                flightOrderChangeList.add(flightOrderChange);
                            }
                        }
                    }
                }
            }
        }
        return flightOrderChangeList;
    }
}
